package com.tau.iplayer.server;

import com.tau.iplayer.client.models.Track;
import com.tau.iplayer.client.YoutubeDataService;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

import com.google.gdata.client.youtube.YouTubeQuery;
import com.google.gdata.client.youtube.YouTubeService;
import com.google.gdata.data.youtube.VideoEntry;
import com.google.gdata.data.youtube.VideoFeed;
import com.google.gdata.data.youtube.YouTubeMediaGroup;
import com.google.gdata.util.ServiceException;
import com.google.gwt.user.server.rpc.RPCServletUtils;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

@SuppressWarnings("serial")
public class YoutubeDataServiceImpl extends RemoteServiceServlet implements
		YoutubeDataService {

	private final static String DEVELOPER_KEY = "AI39si4kanai3VpZUadyVeoRKP_yNwbC_TE-xvjNd-8bPFynSDNUHBgFVdU5OV7WevtCSCB6drLuu9aoK39amJDpZjEE65T1_w";
	private static final int MAX_RESULTS = 30;

	/**
	 * search for a youtube video with the given title
	 * 
	 * @param title
	 *            the title of the video to search
	 * @return the video feed containing the search results
	 */
	public List<Track> searchVideo(String searchTitle) {
		YouTubeService service = new YouTubeService(DEVELOPER_KEY);
		YouTubeQuery query;
		List<Track> searchResults = new ArrayList<Track>();
		try {
			query = new YouTubeQuery(new URL(
					"http://gdata.youtube.com/feeds/api/videos"));
			query.setOrderBy(YouTubeQuery.OrderBy.RELEVANCE);

			query.setFullTextQuery(searchTitle);
			query.setSafeSearch(YouTubeQuery.SafeSearch.NONE);
			query.setMaxResults(MAX_RESULTS);
			VideoFeed videoFeed = service.query(query, VideoFeed.class);
			List<VideoEntry> videoEntries = videoFeed.getEntries();
			if (videoEntries != null && !videoEntries.isEmpty()) {
				for (VideoEntry videoEntry : videoEntries) {
					if (videoEntry.isEmbeddable()) {
						String title = videoEntry.getTitle().getPlainText();
						YouTubeMediaGroup mediaGroup = videoEntry
								.getMediaGroup();
						String id = mediaGroup.getVideoId();
						String thumbnailURL = mediaGroup.getThumbnails().get(0).getUrl();
						int duration = mediaGroup.getYouTubeContents().get(0).getDuration();
						Track searchResult = new Track(title, duration, id, thumbnailURL);
						searchResults.add(searchResult);
					}
				}
			}
		} catch (MalformedURLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ServiceException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return searchResults;
	}
	
	@Override
	protected String readContent(HttpServletRequest request)
			throws ServletException, IOException {
		return RPCServletUtils.readContentAsUtf8(request, false);
	}
}
